package com.mcintyret.scripts;

import com.mcintyret.site.security.PasswordEncrypter;
import com.mcintyret.site.users.User;
import com.mcintyret.site.users.database.UsersDatabaseConfig;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * User: mcintyret2
 * Date: 08/04/2012
 */

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@Import(UsersDatabaseConfig.class)
@PropertySource({"classpath:database.properties", "classpath:local-properties.properties"})
public class ConvertExistingUsers {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public PasswordEncrypter passwordEncrypter() {
        return new PasswordEncrypter();
    }

    @Resource(name = "usersSessionFactory")
    private SessionFactory usersSessionFactory;

    @Resource
    private PasswordEncrypter passwordEncrypter;

    private static ApplicationContext ctx;

    public static void main(String[] args) {
        ctx = new AnnotationConfigApplicationContext(ConvertExistingUsers.class);

//        ctx.getBean(HibernateTransactionManager.class).setHibernateManagedSession(true);

        ConvertExistingUsers ceu = ctx.getBean(ConvertExistingUsers.class);
        ceu.doIt();
    }

    @Transactional("usersTransactionManager")
    public void doIt() {
        Session session = usersSessionFactory.getCurrentSession();

        List<User> users = session.createQuery("from User").list();

        for (User user : users) {
            if (StringUtils.isNotBlank(user.getUuid())) {
                continue;
            }

            user.setUuid(UUID.randomUUID().toString());
            user.setEmail("some@email.com");
            user.setAccountNonExpired(true);
            user.setAccountNonLocked(true);
            user.setEnabled(true);
            user.setCredentialsNonExpired(true);

            passwordEncrypter.encryptUserPassword(user);

            session.update(user);
        }

    }


}
